package org.tis.tools.abf.module.om.controller;

import com.baomidou.mybatisplus.plugins.Page;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.tis.tools.abf.module.ac.controller.request.AcMenuMoveRequest;
import org.tis.tools.abf.module.ac.entity.AcApp;
import org.tis.tools.abf.module.om.controller.request.*;
import org.tis.tools.abf.module.om.entity.OmEmployee;
import org.tis.tools.abf.module.om.entity.OmGroup;
import org.tis.tools.abf.module.om.entity.OmPosition;
import org.tis.tools.abf.module.om.entity.enums.OmGroupType;
import org.tis.tools.abf.module.om.entity.vo.OmGroupPositionDetail;
import org.tis.tools.abf.module.om.service.IOmEmpGroupService;
import org.tis.tools.abf.module.om.service.IOmGroupService;
import org.tis.tools.abf.module.om.service.IOmPositionService;
import org.tis.tools.core.web.controller.BaseController;
import org.tis.tools.core.web.vo.SmartPage;
import org.tis.tools.model.common.ResultVO;
import org.tis.tools.model.exception.ToolsRuntimeException;
import org.tis.tools.model.log.enums.OperateType;
import org.tis.tools.starter.operatelog.annotation.OperateLog;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import javax.validation.groups.Default;
import java.util.List;

/**
 * omGroup的Controller类
 * 
 * @author ljhua
 * @date 2018/04/23
 */
@RestController
@RequestMapping("/omGroups")
@Validated
@Slf4j
public class OmGroupController extends BaseController<OmGroup>  {

    @Autowired
    private IOmGroupService omGroupService;
    @Autowired
    private IOmEmpGroupService omEmpGroupService;
    @Autowired
    private IOmPositionService omPositionService;


    @ApiOperation(value = "条件查询工作组列表",notes = "传入工作组代码(groupCode)作为参数")
    @GetMapping("/{groupCode}")
    public ResultVO detail(@PathVariable @NotBlank(message = "工作组代码不能为空") @ApiParam(value = "groupCode",name = "传入工作组代码",required = true) String groupCode) {
        OmGroup omGroup = omGroupService.selectGroupByCode(groupCode);
        if (omGroup == null) {
            return ResultVO.error("404", "找不到对应记录或已经被删除！");
        }
        return ResultVO.success("查询成功!", omGroup);
    }


    @ApiOperation(value = "分页查询所有工作组列表",notes = "传入分页信息作为参数")
    @PostMapping("/list")
    public ResultVO list(@RequestBody @Validated @ApiParam(value = "page",name = "分页信息",required = true) SmartPage<OmGroup> page) {
        return  ResultVO.success("查询成功！", omGroupService.selectPage(page.getPageObj(), page.getConditionWrapper()));
    }


    @ApiOperation(value = "新增根工作组",notes = "传入OmGroupAddRequest类作为参数")
    @OperateLog(type = OperateType.ADD, desc = "新增根工作组")
    @PostMapping(value = "/root")
    public ResultVO addRoot(@RequestBody @Validated({OmGroupAddRequest.Root.class,Default.class}) @ApiParam(value = "OmGroupAddRequest",name = "传入的OmGroupAddRequest类",required = true) OmGroupAddRequest groupAddRequest) {
        omGroupService.createGroup(groupAddRequest.getGroupType(),groupAddRequest.getGroupName(),groupAddRequest.getGuidOrg(),null,groupAddRequest.getGroupDesc());
        return ResultVO.success("新增成功！");
    }


    @ApiOperation(value = "新增子工作组",notes = "传入OmGroupAddRequest类作为参数")
    @OperateLog(type = OperateType.ADD, desc = "新增子工作组")
    @PostMapping(value = "/child")
    public ResultVO addChild(@RequestBody @Validated(OmGroupAddRequest.Child.class) @ApiParam(value = "OmGroupAddRequest",name = "传入的OmGroupAddRequest类",required = true) OmGroupAddRequest groupAddRequest) {
        omGroupService.createGroup(groupAddRequest.getGroupType(),groupAddRequest.getGroupName(),groupAddRequest.getGuidOrg(),groupAddRequest.getGuidParents(),groupAddRequest.getGroupDesc());
        return ResultVO.success("新增成功！");
    }


    @ApiOperation(value = "删除工作组",notes = "传入工作组代码(groupCode)作为参数")
    @OperateLog(type = OperateType.DELETE, desc = "删除工作组")
    @DeleteMapping(value = "/{groupCode}")
    public ResultVO delete( @PathVariable @NotBlank(message = "groupCode不能为空") @ApiParam(value = "OmGroupAddRequest",name = "传入的OmGroupAddRequest类",required = true) String groupCode) {
        omGroupService.deleteGroup(groupCode);
        return ResultVO.success("删除成功！");
    }


    @ApiOperation(value = "生成工作组代码",notes = "传入工作组状态(groupType)作为参数")
    @OperateLog(type = OperateType.ADD, desc = "生成工作组编号")
    @PostMapping("/{groupType}/initGroupCode")
    public ResultVO initGroupCode(@PathVariable @NotBlank(message = "工作组状态不能为空") @ApiParam(value = "groupType",name = "工作组状态",required = true) OmGroupType groupType) {
        omGroupService.genGroupCode(groupType.getValue());
        return ResultVO.success("生成工作组编号成功！");
    }


    @ApiOperation(value = "启用---注销工作组",notes = "传入工作组代码(groupCode)作为参数")
    @OperateLog(type = OperateType.UPDATE, desc = "更改工作组状态")
    @PutMapping(value = "/{groupCode}/enable")
    public ResultVO enableGroup(@PathVariable @NotBlank(message = "groupCode不能为空") @ApiParam(value = "groupCode",name = "工作组代码",required = true) String groupCode) {
        omGroupService.cancelGroup(groupCode);
        return ResultVO.success("注销成功!");
    }


    @ApiOperation(value = "启用---重启工作组",notes = "传入工作组代码(groupCode)和是否同时重新启用子工作组(reenableChild)作为参数")
    @OperateLog(type = OperateType.UPDATE, desc = "更改工作组状态")
    @PutMapping(value = "/{groupCode}/reenable/{reenableChild}")
    public ResultVO reenableGroup(@PathVariable @NotBlank(message = "groupCode不能为空") @ApiParam(value = "groupCode",name = "工作组代码",required = true) String groupCode, @PathVariable @NotBlank(message = "groupCode不能为空") @ApiParam(value = "reenableChild",name = "是否同时重新启用子工作组",required = true) String reenableChild) {
        omGroupService.reenableGroup(groupCode,reenableChild);
        return ResultVO.success("启用成功!");
    }


    @ApiOperation(value = "更新修改工作组",notes = "传入OmGroupUpdateRequest类作为参数")
    @OperateLog(type = OperateType.UPDATE, desc = "更新工作组")
    @PutMapping
    public ResultVO updateGroup(@RequestBody @Validated @ApiParam(value = "OmGroupUpdateRequest",name = "传入OmGroupUpdateRequest类",required = true) OmGroupUpdateRequest omGroupUpdateRequest) {
        OmGroup og = new OmGroup();
        og.setGuid(omGroupUpdateRequest.getGuid());
        og.setGroupCode(omGroupUpdateRequest.getGroupCode());
        og.setGroupName(omGroupUpdateRequest.getGroupName());
        og.setGroupDesc(omGroupUpdateRequest.getGroupDesc());
        og.setGuidOrg(omGroupUpdateRequest.getGuidOrg());

        boolean isexist = omGroupService.updateGroup(og);
        if (!isexist){
            return ResultVO.error("404","工作组代码已存在,请重新输入!");
        }
        return ResultVO.success("修改成功!");
    }

    /**
     * 生成下级岗位列表
     */
    @RequestMapping(value = "/position")
    public ResultVO loadPosition(@RequestBody String content, String age, HttpServletRequest request,
                               HttpServletResponse response) {
//        try {
//            JSONObject jsonObj = JSONObject.parseObject(content);
//            String groupCode = jsonObj.getString("groupCode");
//            //TODO
//        } catch (ToolsRuntimeException e) {// TODO
//            AjaxUtils.ajaxJsonErrorMessage(response, e.getCode(), e.getMessage());
//            e.printStackTrace();
//        } catch (Exception e) {
//            AjaxUtils.ajaxJsonErrorMessage(response, "SYS_0001", e.getMessage());
//        }
        return null;
    }


    @ApiOperation(value = "查询在此工作组的员工",notes = "传入分页信息(page)和工作组代码(groupCode)作为参数")
    @PostMapping(value = "/{groupCode}/emp")
    public ResultVO loadempin(@PathVariable @NotBlank(message = "groupCode不能为空") @ApiParam(value = "groupCode",name = "工作组代码",required = true) String groupCode, @RequestBody @Validated @ApiParam(value = "page",name = "分页信息",required = true) SmartPage<OmEmployee> page) {
        Page<OmEmployee> omEmployeePage = new Page<OmEmployee>(page.getPage().getCurrent(), page.getPage().getSize(), page.getPage().getOrderByField(), page.getPage().getAsc());

        return ResultVO.success("查询成功!",omGroupService.selectEmployeeFilter(groupCode, omEmployeePage,page.getConditionWrapper()));
    }


    @ApiOperation(value = "加载不在此工作组的人员列表(同属同一机构)",notes = "传入机构GUID(guidOrg)和工作组代码(groupCode)作为参数")
    @GetMapping(value = "/{groupCode}/empNotIn/{guidOrg}")
    public ResultVO loadEmpNotIn(@PathVariable @NotBlank(message = "guidOrg不能为空") @ApiParam(value = "guidOrg",name = "机构GUID",required = true) String guidOrg, @PathVariable @NotBlank(message = "groupCode不能为空") @ApiParam(value = "groupCode",name = "工作组代码",required = true) String groupCode) {

        List<OmEmployee> omEmpList = omGroupService.selectEmpNotInGroup(guidOrg, groupCode);
        return ResultVO.success("查询成功！",omEmpList);
    }


    @ApiOperation(value = "工作组新添人员",notes = "传入OmGroupAddEmpRequest类作为参数")
    @OperateLog(type = OperateType.UPDATE, desc = "工作组新添人员")
    @PostMapping(value = "/empGroup")
    public ResultVO addEmpGroup(@RequestBody @Validated @ApiParam(value = "OmGroupAddEmpRequest",name = "传入的OmGroupAddEmpRequest类",required = true) OmGroupAddEmpRequest omGroupAddEmpRequest) {

        omEmpGroupService.insertGroupEmp(omGroupAddEmpRequest.getGroupCode(), omGroupAddEmpRequest.getGuidEmp());
        return ResultVO.success("新增成功！");
    }


    @ApiOperation(value = "为工作组删除员工",notes = "传入员工GUID(guidEmp)和工作组代码(groupCode)作为参数")
    @OperateLog(type = OperateType.DELETE, desc = "为工作组删除员工")
    @DeleteMapping(value = "/{groupCode}/empGroup/{guidEmp}")
    public ResultVO deleteEmpGroup(@PathVariable @NotBlank(message = "groupCode不能为空") @ApiParam(value = "groupCode",name = "工作组代码",required = true) String groupCode, @PathVariable @NotBlank(message = "guidEmp不能为空") @ApiParam(value = "guidEmp",name = "员工GUID",required = true) String guidEmp) {

        omEmpGroupService.deleteGroupEmp(groupCode,guidEmp);
        return ResultVO.success("删除成功！");
    }


    @ApiOperation(value = "加载下级岗位列表(模糊查询)",notes = "传入分页信息(page)和工作组代码(groupCode)作为参数")
    @PostMapping(value = "/{groupCode}/positionIn")
    public ResultVO loadPositionIn(@PathVariable @NotBlank(message = "groupCode不能为空") @ApiParam(value = "groupCode",name = "工作组代码",required = true) String groupCode, @RequestBody @Validated @ApiParam(value = "page",name = "分页信息",required = true) SmartPage<OmPosition> page) {

        Page<OmPosition> omPositionPage = new Page<OmPosition>(page.getPage().getCurrent(), page.getPage().getSize(),
                page.getPage().getOrderByField(), page.getPage().getAsc());
        Page<OmGroupPositionDetail> pageList = omGroupService.selectPositionInGroup(groupCode,omPositionPage,page
                .getConditionWrapper());
        return ResultVO.success("查询成功！",pageList);
    }


    @ApiOperation(value = "加载下级岗位列表，不分页",notes = "传入工作组代码(groupCode)作为参数")
    @GetMapping(value = "/{groupCode}/positionNotPage")
    public ResultVO loadPositionNotPage(@PathVariable @NotBlank(message = "groupCode不能为空") @ApiParam(value = "groupCode",name = "工作组代码",required = true) String groupCode) {

        List<OmPosition> omList = omGroupService.selectPositionInGroupNotPage(groupCode);
        return ResultVO.success("查询成功！",omList);
    }


//    @ApiOperation(value = "加载不在此工作组的岗位列表(同属同一机构)",notes = "传入分页信息(page)和工作组代码(groupCode)作为参数")
//    @PostMapping(value = "/{groupCode}/availablePosition")
//    public ResultVO loadpositionNotin(@PathVariable @NotBlank(message = "groupCode不能为空") @ApiParam(value = "groupCode",name = "工作组代码",required = true) String groupCode, @RequestBody @Validated @ApiParam(value = "page",name = "分页信息",required = true) SmartPage<OmPosition> page) {
//
//        Page<OmPosition> omPositionPage = new Page<OmPosition>(page.getPage().getCurrent(), page.getPage().getSize(),
//                page.getPage().getOrderByField(), page.getPage().getAsc());
//
//        Page<OmPosition> list = omGroupService.selectPositionNotInGroup(groupCode, omPositionPage);
//        return ResultVO.success("查询成功！",list);
//    }


    @ApiOperation(value = "为工作组新添岗位",notes = "传入OmGroupPositionRequest类作为参数")
    @OperateLog(type = OperateType.ADD,desc = "为工作组新增岗位")
    @PostMapping(value = "/position")
    public ResultVO addGroupPosition(@RequestBody @Validated @ApiParam(value = "OmGroupPositionRequest",name = "传入的OmGroupPositionRequest类",required = true) OmGroupPositionRequest omGroupPositionRequest) {
        if (omPositionService.existAddPositionCode(omGroupPositionRequest.getOmPositionRequest().getPositionCode(),
                omGroupPositionRequest.getOmPositionRequest().getGuidMapping())){
            return ResultVO.error("404", "岗位代码已经存在,请重新输入!");
        }
        omGroupService.insertGroupPosition(omGroupPositionRequest.getGroupCode(), omGroupPositionRequest.getOmPositionRequest());
        return ResultVO.success("新增成功！");
    }


//    @ApiOperation(value = "删除工作组的岗位",notes = "传入岗位GUID(positionGuid)和工作组代码(groupCode)作为参数")
//    @OperateLog(type = OperateType.DELETE,desc = "为工作组删除岗位")
//    @DeleteMapping(value = "/{groupCode}/position/{positionGuid}")
//    public ResultVO deleteGroupPosition(@PathVariable @NotBlank(message = "groupCode不能为空") @ApiParam(value = "groupCode",name = "工作组代码",required = true) String groupCode, @PathVariable @NotBlank(message = "positionGuid不能为空") @ApiParam(value = "positionGuid",name = "岗位GUID",required = true) String positionGuid) {
//        omGroupService.deleteGroupPosition(groupCode,positionGuid);
//        return ResultVO.success("删除成功！");
//    }


    @ApiOperation(value = "查询工作组下的应用",notes = "传入分页信息(page)和工作组代码(groupCode)作为参数")
    @PostMapping(value = "/{groupCode}/app")
    public ResultVO selectApp(@PathVariable @NotBlank(message = "groupCode不能为空") @ApiParam(value = "groupCode",name = "工作组代码",required = true) String groupCode, @RequestBody @Validated @ApiParam(value = "page",name = "分页信息",required = true) SmartPage<AcApp> page) throws ToolsRuntimeException {

        Page<AcApp> acAppPage = new Page<AcApp>(page.getPage().getCurrent(), page.getPage().getSize(),
                page.getPage().getOrderByField(), page.getPage().getAsc());

        Page<AcApp> list = omGroupService.selectApp(groupCode,acAppPage);
        return ResultVO.success("查询成功！",list);
    }


    @ApiOperation(value = "查询可以为工作组添加的应用",notes = "传入工作组代码(groupCode)作为参数")
    @GetMapping(value = "/{groupCode}/availableApp")
    public ResultVO selectNotInApp(@PathVariable @NotBlank(message = "groupCode不能为空") @ApiParam(value = "groupCode",name = "工作组代码",required = true) String groupCode) throws ToolsRuntimeException{

        List<AcApp> list = omGroupService.selectAppNotInGroup(groupCode);
        return ResultVO.success("查询成功！",list);
    }


    @ApiOperation(value = "新增工作组-应用记录",notes = "传入OmGroupAddAppRequest类作为参数")
    @OperateLog(type = OperateType.ADD, desc = "为工作组添加应用")
    @PostMapping(value = "/app")
    public ResultVO addGroupApp(@RequestBody @Validated @ApiParam(value = "OmGroupAddAppRequest",name = "传入的OmGroupAddAppRequest类",required = true) OmGroupAddAppRequest omGroupAddAppRequest) throws ToolsRuntimeException {
        omGroupService.addGroupApp(omGroupAddAppRequest.getAppGuidList(), omGroupAddAppRequest.getGroupCode());

        return ResultVO.success("新增成功！");
    }


    @ApiOperation(value = "删除工作组-应用记录",notes = "传入应用GUID(guidApp)和工作组代码(groupCode)作为参数")
    @OperateLog(type = OperateType.DELETE, desc = "为工作组删除应用")
    @DeleteMapping(value = "/{groupCode}/app/{guidApp}")
    public ResultVO deleteGroupApp(@PathVariable @NotBlank(message = "guidApp不能为空") @ApiParam(value = "guidApp",name = "应用GUID",required = true) String guidApp, @PathVariable @NotBlank(message = "groupCode不能为空") @ApiParam(value = "groupCode",name = "工作组代码",required = true) String groupCode) throws ToolsRuntimeException{
        omGroupService.deleteGroupApp(groupCode, guidApp);
        return ResultVO.success("删除成功");
    }


    @ApiOperation(value = "查询工作组树",notes = "不需要传任何参数")
    @GetMapping("/tree")
    public ResultVO selectGroupTree(){
        return ResultVO.success("查询成功",omGroupService.selectGroupTree());
    }


    @ApiOperation(value = "根据姓名过滤查询查询工作组树",notes = "传入OmTreeQueryParameterRequest类作为参数")
    @PostMapping("/treeFilter")
    public ResultVO selectGroupTreeFilter(@RequestBody @Validated @ApiParam(value = "name",name = "工作组名称",required = true) OmTreeQueryParameterRequest request){
        return ResultVO.success("查询成功",omGroupService.selectGroupTreeFilter(request.getName()));
    }

    @ApiOperation(value = "获取该工作组下可分配给该岗位的员工",notes = "传入工作组代码(groupCode)和岗位GUID(positionGuid)作为参数")
    @GetMapping("/{groupCode}/getPositionOutEmployee/{positionGuid}")
    public ResultVO getPositionOutEmployee(@PathVariable @NotBlank(message = "工作组代码不能为空") @ApiParam(value = "groupCode",name = "工作组代码",required = true) String groupCode, @PathVariable @NotBlank(message = "岗位GUID不能为空") @ApiParam(value = "positionGuid",name = "岗位GUID",required = true) String positionGuid){
        OmGroup omGroup = omGroupService.selectGroupByCode(groupCode);
        if (omGroup == null) {
            return ResultVO.error("404", "找不到对应的工作组记录或已经被删除！");
        }
        return ResultVO.success("查询成功",omGroupService.getPositionOutEmployee(omGroup,positionGuid));
    }

    @ApiOperation(value = "不分页查询工作组下的所属岗位",notes = "传入工作组GUID(groupId)和岗位GUID(positionId)作为参数")
    @PostMapping("/listsByGroupId")
    public ResultVO queryPositionByGroupId(@RequestBody @Validated @ApiParam(name = "OmPositionGroupRequest" ,value ="传入参数OmPositionGroupRequest",required = true) OmPositionGroupRequest omPositionGroupRequest){
        return ResultVO.success("查询成功",omGroupService.queryPositionByGroupId(omPositionGroupRequest.getGroupId(), omPositionGroupRequest.getPositionId()));
    }

    @ApiOperation(value = "移动工作组",notes = "传入AcMenuMoveRequest类作为参数")
    @OperateLog(type = OperateType.UPDATE, desc = "修改工作组（移动）")
    @PostMapping("/queryMoveGroupLists")
    public ResultVO getMoveGroup(@RequestBody @Validated @ApiParam(value = "AcMenuMoveRequest",name = "传入的AcMenuMoveRequest类",required = true) AcMenuMoveRequest acMenuMoveRequest){

        OmGroup omGroup = omGroupService.moveGroup(acMenuMoveRequest.getTargetGuid(),acMenuMoveRequest.getMoveGuid(),
                acMenuMoveRequest.getOrder());
        return ResultVO.success("查询成功",omGroup);
    }
}

